package com.cooba.video_frament;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.cooba.R;
import com.cooba.activitys.VideoDetailsActivity;
import com.cooba.bean.VideoBeans;
import com.cooba.pullTorefresh.PullToRefreshBase;
import com.cooba.pullTorefresh.PullToRefreshGridView;
import com.cooba.utils.CommonUtil;
import com.cooba.utils.ServerURL;
import com.google.gson.Gson;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2015/12/29.
 * 电影
 */
public class FilmFrament extends Fragment {
    private View view;
    private HttpUtils httpUtils;
    private RequestParams params;
    private PullToRefreshGridView mGridView;
    private List<VideoBeans.VideoListEntity> list = new ArrayList<>();

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        try {
            if (view == null) {
                view = initview(inflater);
            }
            return view;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

    private View initview(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.video_baseframent, null, false);

        initPullTorefresh(view);
        return view;
    }

    private void initPullTorefresh(View view) {
        mGridView = (PullToRefreshGridView) view.findViewById(R.id.gridview);
        getData("0", false);
        mGridView.setLastUpdatedLabel("");
        mGridView.setPullLoadEnabled(true);  //上拉加载，屏蔽
        mGridView.setPullRefreshEnabled(true);
        mGridView.setScrollLoadEnabled(true); //设置滚动加载可用
        mGridView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<GridView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {
                getData("0", false);
                String stringDate = CommonUtil.getStringDate();
                mGridView.setLastUpdatedLabel(stringDate);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView) {
                if (CommonUtil.isNetWork(getActivity())) {
                    getDataUp("1", true);
                } else {
                    Toast.makeText(getActivity(), "网络错误", Toast.LENGTH_SHORT).show();
                }

            }
        });
        mGridView.getRefreshableView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String videoUrl = mAdapter.getList().get(position).getVideo_page_url().toString().replaceAll("\\\\", "");
                String videoTitle = mAdapter.getList().get(position).getTitle().toString();
                String videoDs = mAdapter.getList().get(position).getIntro().toString();
                Intent intent = new Intent(getActivity(), VideoDetailsActivity.class);
                intent.putExtra("videoUrl", videoUrl);
                intent.putExtra("videoTitle", videoTitle);
                intent.putExtra("videoDs", videoDs);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.zcdh_set_in, R.anim.zcdh_alpha_out);
            }
        });
    }
    private void getData(String next_key, final boolean isfenye) {
        httpUtils = new HttpUtils();
        params = new RequestParams();
        params.addBodyParameter("dir_name", "hot");
        params.addBodyParameter("next_key", "0");
        params.addBodyParameter("page_size", "10");
        httpUtils.send(HttpRequest.HttpMethod.POST, ServerURL.httpUrl + ServerURL.queryVideoList, params, new RequestCallBack<String>() {
            @Override
            public void onFailure(HttpException arg0, String arg1) {
                Log.e("sss", "获取失败");
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                paserData(responseInfo.result, isfenye);
            }
        });

    }
    private void getDataUp(String next_key, final boolean isfenye) {
        httpUtils = new HttpUtils();
        params = new RequestParams();
        params.addBodyParameter("dir_name", "hot");
        params.addBodyParameter("next_key", "10");
        params.addBodyParameter("page_size", "10");
        httpUtils.send(HttpRequest.HttpMethod.POST, ServerURL.httpUrl + ServerURL.queryVideoList, params, new RequestCallBack<String>() {
            @Override
            public void onFailure(HttpException arg0, String arg1) {
                Log.e("sss", "获取失败");
            }
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                paserData(responseInfo.result, isfenye);
            }
        });

    }

    private VideoMyadapter mAdapter;

    //解析数据并添加到集合
    private void paserData(String result, boolean isfenye) {
        if (!isfenye) {
            list.clear();
        }

        VideoBeans shitingBean = new Gson().fromJson(result, VideoBeans.class);
        if (mAdapter == null) {
            mAdapter = new VideoMyadapter(getContext(), shitingBean.videoList);
            mGridView.getRefreshableView().setAdapter(mAdapter);
        } else {
            list.addAll(shitingBean.videoList);
            mAdapter.setList(list);
        }
        mGridView.onPullDownRefreshComplete();
        mGridView.onPullUpRefreshComplete();
    }

    class VideoMyadapter extends BaseAdapter {
        private Context context;
        private List<VideoBeans.VideoListEntity> list;

        public List<VideoBeans.VideoListEntity> getList() {
            return list;
        }

        public void setList(List<VideoBeans.VideoListEntity> list) {
            this.list = list;
            notifyDataSetChanged();
        }

        public VideoMyadapter(Context context, List<VideoBeans.VideoListEntity> list) {
            this.context = context;
            this.list = list;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            VideoViewHolder holder = null;
            if (convertView == null) {
                holder = new VideoViewHolder();
                convertView = LayoutInflater.from((context)).inflate(R.layout.video_list_item, parent, false);
                holder.img = (ImageView) convertView.findViewById(R.id.iv_video);
                holder.description = (TextView) convertView.findViewById(R.id.tv_video);
                holder.title = (TextView) convertView.findViewById(R.id.tv_videomsg);
                convertView.setTag(holder);
            } else {
                holder = (VideoViewHolder) convertView.getTag();
            }

            holder.title.setText(list.get(position).getTitle());
            holder.description.setText(list.get(position).getIntro());
            String imgUrl = list.get(position).getImg_url();

            BitmapUtils bitmapUtils = new BitmapUtils(context);
            bitmapUtils.display(holder.img, imgUrl);

            return convertView;
        }

        class VideoViewHolder {

            private ImageView img;
            public TextView title;
            public TextView description;

        }

    }


}
